const { FieldType } = require('../models');
const { buildPaginationResponse } = require('../middleware/pagination');

// 获取字段类型列表
const getFieldTypes = async (req, res) => {
  try {
    const { category, isActive } = req.query;

    // 构建查询条件
    const query = {};
    if (category) query.category = category;
    if (isActive !== undefined) query.isActive = isActive === 'true';

    const fieldTypes = await FieldType.find(query)
      .sort({ category: 1, name: 1 });

    res.json({
      success: true,
      data: fieldTypes
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取字段类型列表失败',
      error: error.message
    });
  }
};

// 获取字段类型详情
const getFieldType = async (req, res) => {
  try {
    const { type } = req.params;

    const fieldType = await FieldType.findOne({ type });

    if (!fieldType) {
      return res.status(404).json({
        success: false,
        message: '字段类型未找到'
      });
    }

    res.json({
      success: true,
      data: fieldType
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取字段类型详情失败',
      error: error.message
    });
  }
};

// 验证字段值
const validateFieldValue = async (req, res) => {
  try {
    const { type } = req.params;
    const { value } = req.body;

    const fieldType = await FieldType.findOne({ type, isActive: true });

    if (!fieldType) {
      return res.status(404).json({
        success: false,
        message: '字段类型未找到'
      });
    }

    // 这里可以添加更复杂的验证逻辑
    // 使用 fieldType.valueSchema 进行验证
    // 现在先返回基本的验证结果

    res.json({
      success: true,
      message: '字段值验证通过',
      data: {
        isValid: true,
        fieldType: fieldType.type,
        validatedValue: value
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '字段值验证失败',
      error: error.message
    });
  }
};

// 创建字段类型（仅管理员）
const createFieldType = async (req, res) => {
  try {
    const fieldType = new FieldType(req.body);
    await fieldType.save();

    res.status(201).json({
      success: true,
      message: '字段类型创建成功',
      data: fieldType
    });
  } catch (error) {
    if (error.code === 11000) {
      return res.status(400).json({
        success: false,
        message: '字段类型标识符已存在'
      });
    }
    res.status(500).json({
      success: false,
      message: '创建字段类型失败',
      error: error.message
    });
  }
};

// 更新字段类型（仅管理员）
const updateFieldType = async (req, res) => {
  try {
    const { type } = req.params;

    const fieldType = await FieldType.findOneAndUpdate(
      { type },
      req.body,
      { new: true, runValidators: true }
    );

    if (!fieldType) {
      return res.status(404).json({
        success: false,
        message: '字段类型未找到'
      });
    }

    res.json({
      success: true,
      message: '字段类型更新成功',
      data: fieldType
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '更新字段类型失败',
      error: error.message
    });
  }
};

module.exports = {
  getFieldTypes,
  getFieldType,
  validateFieldValue,
  createFieldType,
  updateFieldType
};